package com.huitone.smspfm.oldclient.model;


import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import com.bin.common.utils.StringUtils;

public class MtGroup implements Serializable {
	
	private static final long serialVersionUID = 1L;

	private String groupKey = null;

	private int count = 0;
	
	private Date lastAddTime = new Date();
	
	private Map<Integer, MtSms> items = new HashMap<>();
	
	public boolean sendAble() {
		boolean sendAble = true;
		for (int i = 1 ; i <= count ; i ++) {
			if (!items.containsKey(i)) {
				sendAble = false;
				break;
			}
		}
		return sendAble;
	}
	
	public void addItem(MtSms mtSms) {
		
		if (mtSms == null) return;
		
		lastAddTime = new Date();
		
		int splitIndex = mtSms.getSplitIndex();
		if (splitIndex == 0) {
			splitIndex = 1;
			count = 1;
		}
		items.put(splitIndex, mtSms);
	}
	
	public void groupMerge(MtGroup mtGroup) {
		if (mtGroup != null) {
			Map<Integer, MtSms> items = mtGroup.getItems();
			Iterator<Entry<Integer, MtSms>> iterator = items.entrySet().iterator();
			while(iterator.hasNext()) {
				this.addItem(iterator.next().getValue());
			}
		}
	}
	
	public MtSms merged() {
		MtSms mtSms = null;
		if (count == 1) { // count==1时为普通短信
			mtSms = items.get(1);
			mtSms.setOldserialnos(mtSms.getSerialno());
			return mtSms;
		} else if (count > 1) { // count > 1 时为长短信
			mtSms = new MtSms();
			for (int i = 1 ; i <= count ; i ++) {
				if (items.containsKey(i)) {
					MtSms tmp = items.get(i);
					mtSms.setSerialno(tmp.getSerialno());
					mtSms.setClientname(tmp.getClientname());
					mtSms.setServiceCode(tmp.getServiceCode());
					mtSms.setSendport(tmp.getSendport());
					mtSms.setMobileno(tmp.getMobileno());
					mtSms.setMesgtype(tmp.getMesgtype());
					mtSms.setSrr(tmp.getSrr());
					mtSms.setCrttime(tmp.getCrttime());
					mtSms.setContent(StringUtils.toString(mtSms.getContent()) + StringUtils.toString(tmp.getContent()));
					String string = StringUtils.toString(mtSms.getOldserialnos());
					if (StringUtils.isEmpty(string)) {
						mtSms.setOldserialnos(StringUtils.toString(tmp.getSerialno()));
					} else {
						mtSms.setOldserialnos(string + "," + StringUtils.toString(tmp.getSerialno()));
					}
				}
			}
		}
		return mtSms;
	}

	public String getGroupKey() {
		return groupKey;
	}

	public void setGroupKey(String groupKey) {
		this.groupKey = groupKey;
	}

	public int getCount() {
		return count;
	}

	public void setCount(int count) {
		this.count = count;
	}

	public Map<Integer, MtSms> getItems() {
		return items;
	}

	public Date getLastAddTime() {
		return lastAddTime;
	}

	public void setLastAddTime(Date lastAddTime) {
		this.lastAddTime = lastAddTime;
	}
}
